<?php
/*
 * СПВ
 **/
class SP_Form_SimpleForm extends SP_Form_AForm
{
	private $fields=array();
	public $attributes=array();
	public $name;
	public $method='post';
	public $action='';
	private $data;
	
	public function __construct($attr=null)
	{
		if(is_array($attr))
		{
			foreach($attr as $key => $value)
			{
				$this->$key=$value;
			}
		}
	}
	
	public function getLabel($name)
	{
		return $this->getField($name)->getLabel();
	}
	
	public function getError($name)
	{
		return $this->getField($name)->getError();
	}
	
	public function getHtml($name)
	{
		return $this->getField($name)->getHtml();
	}
	
	public function getValue($name)
	{
		return $this->getField($name)->getValue();
	}
	
	public function setValue($name, $value)
	{
		 $this->getField($name)->setValue($value);
	}
	
	public function getValues()
	{
		$array=array();
		foreach($this->fields as $field)
		{
			$array[$field->getName()]=$field->getValue();
		}
		return $array;
	}
	
	public function setName($value)
	{
		 $this->name=$value;
		 return $this;
	}
	
	public function getName()
	{
		return $this->name;
	}
	
	public function setMethod($value)
	{
		 $this->method=$value;
		 return $this;
	}
	
	public function setAction($value)
	{
		 $this->action=$value;
		 return $this;
	}
	
	public function setField($field)
	{
		$name=$field->getName();
		if( $this->hasField($name) ) throw new exception('Field with name "'.$name.'" already exist');
		$field->form_name=$this->name;
		$this->fields[$field->name]=$field;
		return $this;
	}
	
	public function setFields($fields)
	{
		foreach($fields as $field)
		{
			$this->setField($field);
		}
	}
	
	public function hasField($name)
	{
		return isset($this->fields[$name]);
	}
	
	public function getField($name)
	{
		if( !$this->hasField($name) ) throw new exception('Form "'.$this->name.'" has not "'.$name.'" field');
		return $this->fields[$name];
	}
	
	public function getFormTagHtml()
	{
		$attributes=SP_Helper_Html::makeAttributes($this->attributes);
		$out='<form action="'.$this->action.'" method="'.$this->method.'"'.$attributes.'>';
		return $out;
	}
	
	public function getFormHtml()
	{
		$out=$this->getFormTagHtml().'<table>';
		foreach($this->fields as $field)
		{
			$out.='<tr><td>'.$field->getLabel().'</td><td>'.$field->getHtml().'</td><td>'.$field->getError().'</td></tr>';
		}
		$out.='</table></form>';
		return $out;
	}
	
	public function getFormError($name)
	{
		return $this->form_errors[$name];
	}
	
	public function setFormError($name, $value)
	{
		$this->form_errors[$name]=$value;
	}
	
	public function validate()
	{
		$result=true;
		foreach($this->fields as $field)
		{
			$result = $result * $field->validate();
		}
		return $result;
	}
	
	public function fill($array)
	{
		foreach($this->fields as $field)
		{
			if( array_key_exists($field->getName(), $array) )
			{
				$field->setValue($array[$field->getName()]);
			}
		}
	}
	
}